package com.dk.controller;


import com.alibaba.fastjson.JSONObject;
import com.dk.pojo.Car;
import com.dk.service.CarServiceFeign;
import com.dk.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("car")
@Controller
public class CarController {

   /* @Autowired
    private RestTemplate restTemplate;*/


    @Autowired
    private CarServiceFeign carServiceFeign;

    //跳转展示页面
    @GetMapping("toShow")
    public String toShow(Model model) {
        /* RestTemplate restTemplate = new RestTemplate();*/
       /* Result result = restTemplate.getForObject("http://car-service/car", Result.class);*/
        Result carList1 = carServiceFeign.findCarList();
        Object date = carList1.getDate();
        /*List<Car> carList = JSON.parseArray(JSONObject.toJSONString(carList1.getDate()), Car.class);*/
        model.addAttribute("carList", date);
        return "show";
    }


    //跳转增加页面
    @RequestMapping("toAdd")
    public String getList() {
        return "add";
    }

    //增加
    @RequestMapping("addCar")
    public String addCar(Car car) {
        /*  RestTemplate restTemplate = new RestTemplate();*/
        /*restTemplate.postForEntity("http://CAR-SERVICE/car", car, Result.class);*/
        carServiceFeign.saveCar(car);
        return "redirect:/car/toShow";
    }

    //删除
    @RequestMapping("deleteById")
    public String deleteById(Integer carId) {
        /* RestTemplate restTemplate = new RestTemplate();*/
        /*restTemplate.delete("http://CAR-SERVICE/car/{carId}", carId);*/
        carServiceFeign.deleteCarList(carId);
        return "redirect:/car/toShow";
    }

    //跳转修改页面
    @RequestMapping("toUpdate")
    public String toUpdate(Model model, Integer carId) {
        /* RestTemplate restTemplate = new RestTemplate();*/
        /*Result result = restTemplate.getForObject("http://CAR-SERVICE/car/" + carId, Result.class);*/
        Result result = carServiceFeign.findCarList(carId);
        Object data = result.getDate();  //data是linkdhashmap
        Car car = JSONObject.parseObject(JSONObject.toJSONString(data), Car.class);
        model.addAttribute("car", car);
        return "update";
    }

    //修改
    @RequestMapping("updateCar")
    public String deleteById(Car car) {
        /* RestTemplate restTemplate = new RestTemplate();*/
       /* restTemplate.put("http://CAR-SERVICE/car", car, Result.class);*/
        carServiceFeign.updateCar(car);
        return "redirect:/car/toShow";
    }
}
